<template>
  <div class="training-management">
    <div class="table-header">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索员工姓名/课程名称"
        style="width: 300px"
        clearable
        @clear="handleSearch"
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
          </el-button>
        </template>
      </el-input>

      <!-- <el-button type="primary" @click="$emit('add-training')">
        <el-icon>
          <Plus />
        </el-icon>
        新增培训记录
      </el-button> -->
    </div>

    <el-table
      :data="filteredTrainings"
      style="width: 100%"
      v-loading="loading"
      stripe
    >
      <el-table-column type="index" label="培训ID" width="100" align="center" />
      <el-table-column
        prop="employeeName"
        label="员工姓名"
        width="120"
        align="center"
      />
      <el-table-column
        prop="courseName"
        label="课程名称"
        min-width="180"
        align="center"
      />
      <el-table-column
        prop="courseType"
        label="课程类型"
        width="120"
        align="center"
      >
        <template #default="scope">
          <el-tag :type="getCourseTypeTag(scope.row.courseType)">
            {{ scope.row.courseType }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="trainingDate"
        label="培训日期"
        width="120"
        align="center"
      />
      <el-table-column prop="score" label="考核分数" width="100" align="center">
        <template #default="scope">
          <el-tag :type="getScoreType(scope.row.score)">
            {{ scope.row.score }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="trainingHours"
        label="培训时长"
        width="100"
        align="center"
      >
        <template #default="scope">
          {{ scope.row.trainingHours }}小时
        </template>
      </el-table-column>
      <el-table-column
        prop="instructor"
        label="讲师"
        width="120"
        align="center"
      />
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === '已完成' ? 'success' : 'warning'">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="certificate"
        label="证书"
        width="120"
        align="center"
      >
        <template #default="scope">
          <el-tag v-if="scope.row.certificate" type="success">有</el-tag>
          <el-tag v-else type="info">无</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            link
            @click="$emit('edit-training', scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            link
            @click="$emit('delete-training', scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from "vue";
import api from "@/services/api";

export default {
  name: "TrainingManagement",
  props: {
    trainings: {
      type: Array,
      default: () => [],
    },
    employees: {
      type: Array,
      default: () => [],
    },
    name: {
      type: String,
      default: () => "",
    },
  },
  emits: ["add-training", "edit-training", "delete-training"],
  setup(props) {
    const searchKeyword = ref("");
    const currentPage = ref(1);
    const pageSize = ref(10);
    const loading = ref(false);
    const filteredTrainings = ref(props.trainings);
    watch(
      () => props.name,
      async (val) => {
        searchKeyword.value = val;
        await api
          .getTrainingRecordByName(val)
          .then((response) => {
            filteredTrainings.value = response.data;
          })
          .catch((error) => {
            console.error("搜索员工/课程失败:", error);
          });
      },
      { immediate: true }
    );

    // watch(
    //   () => props.trainings,
    //   async () => {
    //     try {
    //       const resTrainings = await api.getTrainings();
    //       filteredTrainings.value = resTrainings.data;
    //     } catch (error) {
    //       console.error("加载培训数据失败:", error);
    //     }
    //   }
    // );

    onMounted(async () => {
      if (props.name) {
        return;
      } else {
        try {
          const resTrainings = await api.getTrainings();
          filteredTrainings.value = resTrainings.data;
        } catch (error) {
          console.error("加载培训数据失败:", error);
        }
      }
    });

    const total = computed(() => {
      if (searchKeyword.value) {
        return props.trainings.filter(
          (training) =>
            training.courseName.includes(searchKeyword.value) ||
            training.employee?.name?.includes(searchKeyword.value)
        ).length;
      }
      return props.trainings.length;
    });

    const getCourseTypeTag = (type) => {
      const typeMap = {
        技术培训: "primary",
        管理培训: "success",
        业务培训: "warning",
        软技能: "info",
        认证培训: "danger",
      };
      return typeMap[type] || "info";
    };

    const getScoreType = (score) => {
      if (score >= 9) return "success";
      if (score >= 7) return "warning";
      return "danger";
    };

    const handleSearch = async () => {
      currentPage.value = 1;
      if (
        searchKeyword.value === "" ||
        searchKeyword.value === null ||
        searchKeyword.value === undefined
      ) {
        try {
          const resTrainings = await api.getTrainings();
          filteredTrainings.value = resTrainings.data;
        } catch (error) {
          console.error("加载培训数据失败:", error);
        }
      } else {
        await api
          .getTrainingRecordByName(searchKeyword.value)
          .then((response) => {
            filteredTrainings.value = response.data;
          })
          .catch((error) => {
            console.error("搜索员工/课程失败:", error);
          });
      }
    };

    const handleSizeChange = (newSize) => {
      pageSize.value = newSize;
      currentPage.value = 1;
    };

    const handleCurrentChange = (newPage) => {
      currentPage.value = newPage;
    };

    return {
      searchKeyword,
      currentPage,
      pageSize,
      loading,
      filteredTrainings,
      total,
      getCourseTypeTag,
      getScoreType,
      handleSearch,
      handleSizeChange,
      handleCurrentChange,
    };
  },
};
</script>

<style scoped>
.training-management {
  padding: 20px 0;
}

.table-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
